package chapter05.s08regexp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式 描述字符串的语法规则 的字符串。
 * 应用：常见的注册邮箱、手机号等操作，一般都会做限制长度、格式等
 * <p>
 * Boundary matchers
 * ^ The beginning of a line
 * $ The end of a line
 * <p>
 * Character classes
 * [abc] a, b, or c (simple class)
 * [^abc] Any character except a, b, or c (negation)
 * [a-zA-Z] a through z or A through Z, inclusive (range)
 * <p>
 * Predefined character classes
 * . Any character (may or may not match line terminators)
 * \d A digit: [0-9]
 * \D A non-digit: [^0-9]
 * \h A horizontal whitespace character: [ \t\xA0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000]
 * \H A non-horizontal whitespace character: [^\h]
 * \s A whitespace character: [ \t\n\x0B\f\r]
 * \S A non-whitespace character: [^\s]
 * \v A vertical whitespace character: [\n\x0B\f\r\x85\u2028\u2029]
 * \V A non-vertical whitespace character: [^\v]
 * \w A word character: [a-zA-Z_0-9]
 * \W A non-word character: [^\w]
 * <p>
 * Greedy quantifiers
 * X? X, once or not at all
 * X* X, zero or more times
 * X+ X, one or more times
 * X{n} X, exactly n times
 * X{n,} X, at least n times
 * X{n,m} X, at least n but not more than m times
 */
public class TestEmail {
    public static void main(String[] args) {
        // email规则: username@xxx.xxx.com
        // ^: 匹配一行的开始
        // \w: A word character: [a-zA-Z_0-9]
        // +: one or more times
        // $: 匹配一行的结束
        String regexp = "^\\w+@\\w+(\\.\\w+)*$";

        // 正则表达式对象
        Pattern pattern = Pattern.compile(regexp);

        // 匹配对象
        Matcher matcher = pattern.matcher("zhujiale@niit.edu.cn");

        // 整个字符串与正则表达式匹配
        boolean isMatched = matcher.matches();

        System.out.println(isMatched);

        // 匹配失败的情况
        matcher = pattern.matcher("zhu#jiale@niit.edu.cn");

        // 整个字符串与正则表达式匹配
        isMatched = matcher.matches();

        System.out.println(isMatched);

    }
}
